using Microsoft.AspNetCore.Authentication.JwtBearer;
using User.Application.Commands;
using User.Infrastructure;


var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi

builder.Services.AddCors(options =>
{
    options.AddPolicy("GatewayProxy", policy =>
    {
        policy.WithOrigins("http://localhost:5173") // 不能用 "*"，要写前端实际 origin
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials(); // 允许带凭据
    });
});
builder.Services.AddOpenApi();
builder.Services.AddControllers();

builder.Services.AddUserEfCore( builder.Configuration);


builder.Services.AddMediatR(cfg =>
{
    cfg.RegisterServicesFromAssembly(typeof(RegisterUserCommandHandler).Assembly);
});

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
    {
        options.Authority = "https://localhost:7291"; // 你的 IdentityService 地址
        options.Audience = "api"; // 你 User API 在 IdentityServer 中对应的 scope/audience
        options.RequireHttpsMetadata = true;

        // 如果是开发用自签名证书，临时放宽（仅开发时使用）
        // options.BackchannelHttpHandler = new HttpClientHandler
        // {
        //     ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
        // };
    });
    
builder.Services.AddAuthorization();

var app = builder.Build();

app.UseRouting();


app.UseCors("GatewayProxy");
app.UseAuthentication();
app.UseAuthorization();


// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}

app.UseHttpsRedirection();


app.MapControllers();

app.Run();

